
--*********************************************************************
--*  Exports the specified mesh to the engines file format
--*  
fn exportMesh pMesh pMaterial = 
(	
	local partCollections = buildPartCollections pMesh pMaterial
	local numParts = undefined
	numParts = partCollections.count

	if (writeshort gFilestream numParts) == false then
		print "error"
		
	for i = 1 to numParts do
	(
		print ("writing part:" + (i as string))
		partMaterial = partCollections[i][1] 
		partIndicies = partCollections[i][2] 
		--print ("writing mesh part: " + (i as string))
		exportMeshPartData pMesh partMaterial partIndicies

	)
	
)

--*********************************************************************
--*  Exports an LOD of the specified mesh
--*  
fn exportMeshLODs numLOD pName pMesh pMaterial = 
(
	if numLOD == 0 then
		numLOD = 1
	
	if pName == undefined or pMesh == undefined or pMaterial == undefined then
		return
	
	local thresholdInc = undefined 
	local normalThreshold = undefined
	
	thresholdInc = (1.0 / numLOD)
	normalThreshold = 0.0
	writeshort gFilestream numLOD
	
	for i = 1 to numLOD do
	(
		local opMesh = snapshot pMesh
		local opMod = optimize ()
		opMod.preservemat1 = true
		opMod.preservesmooth1 = false
		opMod.autoedge = true
		opMod.edgethreshold1 = 0.000005
		opMod.bias1 = 0
		opMod.facethreshold1 = normalThreshold * 10.0
		
		addModifier opMesh opMod
		collapseStack opMesh 
		
		--meshop.optimize opMesh normalThreshold 0.000005 0 0 saveMatBoundries:true saveSmoothBoundries:false autoEdge:true
		if opMesh != undefined then
		(
			exportMesh opMesh pMaterial
		)
		normalThreshold += thresholdInc
		
		delete opMesh
	)
)

--*********************************************************************
--*  Exports the specified mesh to the engines file format
--*  
fn exportStaticMesh numLOD:1 pName:"" = 
(
	for oMesh in selection do
	(
		if ((isKindOf oMesh Editable_Mesh) or  (isKindOf oMesh Editable_Poly)) do 
		(			
			safeMesh = convertToPoly (oMesh)
			if safeMesh != undefined then
			(
				update oMesh 
						
				openOutputFile ((getFilenameFile maxFileName) +  ".mdl")
			
				local pMesh = /*snapshotAsMesh*/ oMesh
			
								
 
				--This is a version check value
				writeshort gFilestream 200
				
				if ((gExportBakedCoordinates == true) and ((polyop.getNumMaps pMesh) > 1)) then
				(
					exportAmbientOcclusion oMesh 
					writeFileStr ((oMesh.name as string) + "_ao_map.jpg")
				)
				else
					writeFileStr (undefined)
					--writeshort gFilestream 0
				
				exportMeshLODs numLOD pName pMesh oMesh.material
				
				--This is like a checksum
				writeshort gFilestream 101
				
				closeOutputFile()
			)
		)
	)
)
